<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Licensed ( https://opensource.org/licenses/MIT )
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// +----------------------------------------------------------------------
// | 授权管理
// +----------------------------------------------------------------------
namespace app\sso\http\api\admin;

use app\sso\model\UserAuthModel;
use app\sso\model\UserModel;
use Inphp\Core\Config;
use Inphp\Core\Db\PDO\Query;
use Inphp\Core\Modules;
use Inphp\Core\Object\Message;
use Inphp\Core\Util\Str;

#[\app\admin\attributes\auth(null, true)] class auth
{
    /**
     * 配置
     * @return array
     */
    public function config(): array
    {
        $config = Modules::getModule("sso")->getConfig("auth");
        return $config ?? [];
    }

    /**
     * 保存配置，配置保存后，会生成一个配置文件到 public/sso/config.php
     * @return Message
     */
    public function saveConfig(): Message
    {
        $smsAutoRegister = POST("smsAutoRegister");
        $smsAutoRegister = $smsAutoRegister == 1;
        $thirdPartyAutoRegister = POST("thirdPartyAutoRegister");
        $thirdPartyAutoRegister = $thirdPartyAutoRegister == 1;
        //短信有效时间
        $tokenLifeTime = POST("tokenLifeTime");
        $tokenLifeTime = is_numeric($tokenLifeTime) && $tokenLifeTime > 3600 ? ceil($tokenLifeTime) : 0;

        //组合
        $auth = compact("smsAutoRegister", "thirdPartyAutoRegister", "tokenLifeTime");
        //打包
        $config = Modules::getModule("sso")->getConfig(null, "config");
        $config = array_merge($config, ["auth" => $auth]);
        if (Modules::getModule("sso")->saveConfig("config", $config)) {
            return httpMessage(0, "配置保存成功");
        }
        return httpMessage(9, "保存配置失败");
    }

    public function list(): array
    {
        //查询
        $db = UserAuthModel::emptyQuery("a")
            ->join(UserModel::tableName()." u", "a.uid=u.uid")
            ->select([
                "a.id, a.uid, a.ip, a.time, a.state, a.errorCode, a.token, a.expireTime, a.type, a.tpId, a.appId",
                "u.username, u.countryCode, u.phone, u.nickname, u.face, u.admin, u.state as userState"
            ]);

        //短信状态
        $state = GET("state");
        $state = $state == 1 || $state == '0' ? $state : null;
        if (!is_null($state)) {
            $db->where("a.state", $state);
        }

        //发送状态
        $userState = GET("userState");
        $userState = $userState == 1 || $userState == 2 || $userState == 3 || $userState == '0' ? $userState : null;
        if (!is_null($userState)) {
            $db->where("u.state", $userState);
        }

        //搜索
        $keyword = GET("keyword");
        $keyword = !empty($keyword) ? Str::trim($keyword) : null;
        if (!empty($keyword)) {
            if (is_numeric($keyword) && strlen($keyword) < 12) {
                //数字，查询手机号码
                $db->whereLike("u.phone", "%{$keyword}%");
            } else {
                //其它，查询昵称
                $db->where(function(Query $q) use($keyword) {
                    $q->whereLike("u.username", "%{$keyword}%")
                        ->orWhereLike("from_base64(substr(u.nickname, 23))", "%{$keyword}%");
                });
            }
        }

        //行数
        $rows = $db->rows();
        //当前页数
        $page = GET('page', 1);
        $page = is_numeric($page) && $page > 0 ? ceil($page) : 1;
        //总页数
        $pages = 1;
        //列表数据
        $list = [];
        if ($rows > 0) {
            $total = GET("total", 30);
            $total = is_numeric($total) && $total > 2 ? $total : 30;
            $pages = ceil($rows / $total);
            $page = $page > $pages ? $pages : $page;
            $offset = $total * ($page - 1);
            $list = $db->orderBy("a.id", "desc")->get($total, $offset);
            foreach ($list as &$item)
            {
                $item['nickname'] = UserModel::decodeNickname($item['nickname']);
                $item['face'] = attachmentUrl($item['face']);
            }
        }
        //返回列表数据，包含行数、页码、总页数、数据列表
        return compact("rows", "page", "pages", "list");
    }
}